package utils

import (
	"encoding/base64"
	"github.com/mojocn/base64Captcha"
	"net/http"
	"sync"
)

var captchaStore = base64Captcha.DefaultMemStore

var (
	once            sync.Once
	captchaInstance *base64Captcha.Captcha
)

func InitCaptcha() {
	once.Do(func() {
		driver := base64Captcha.NewDriverDigit(80, 240, 4, 0, 50)
		captchaInstance = base64Captcha.NewCaptcha(driver, captchaStore)
	})
}

// 生成验证码，直接写图片到响应，返回验证码ID
func GenerateCaptchaImage(w http.ResponseWriter, r *http.Request) (string, error) {
	InitCaptcha()

	// 生成验证码ID，内容，答案，错误
	id, content, _, err := captchaInstance.Generate()
	if err != nil {
		return "", err
	}

	// content 格式: 
	const prefix = "data:image/png;base64,"
	if len(content) <= len(prefix) {
		return "", err
	}

	base64Data := content[len(prefix):] // 取纯base64部分

	// base64 解码
	imgBytes, err := base64.StdEncoding.DecodeString(base64Data)
	if err != nil {
		return "", err
	}

	// 设置响应头，输出PNG图片
	w.Header().Set("Content-Type", "image/png")
	// 设置响应头，把验证码 ID 放进去，让前端可以拿到
	w.Header().Set("Captcha-ID", id)
	_, err = w.Write(imgBytes)
	if err != nil {
		return "", err
	}

	return id, nil
}

// 校验验证码
func VerifyCaptcha(id, value string) bool {
	return captchaStore.Verify(id, value, true)
}
